<template>
<div>
  <!--导航区域-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>活动管理</el-breadcrumb-item>
    <el-breadcrumb-item>活动管理</el-breadcrumb-item>
  </el-breadcrumb>

  <!--搜索框-->
  <el-card >
    <!--gutter栅格间隔距离-->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-input clearable v-model="queryInfo.query" placeholder="请输入内容" @clear="clearSearch">
          <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </el-col >
               <!--添加用户-->
      <el-col :span="4">
        <!--添加用户的对话框-->
        <el-button type="primary" @click="dialogTableVisible=true">添加用户</el-button>

      </el-col>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <!-- 添加索引 -->
        <el-table-column type="index" label="#" width="100px"></el-table-column>
        <el-table-column prop="username" label="姓名" width="100px"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="100px"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="100px"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="100px"></el-table-column>
        <!--监听状态
        状态改变时，发出请求，改变状态
        更新失败，提示用户，状态取反；更新成功，提示用户。-->
        <el-table-column  label="状态" width="180">
          <!-- 自定义状态列显示
     使用作用域插槽，scope.row获取当前行的数据 -->
          <template v-slot="scope">
            <el-switch
                @change="userStateChange(scope.row)"
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"></el-switch>
          </template>
        </el-table-column>

        <el-table-column  label="操作" width="180">
          <template slot-scope="scope">
            <!--修改用户 @click中方法作用用来显示或者隐藏对话框，在对话框的确定按钮中才是提交数据的 -->
            <el-tooltip effect="dark"  content="编辑用户" placement="top" :enterable="false">
            <el-button type="primary" icon="el-icon-edit"  @click="updatavisible=true"  circle></el-button>
            </el-tooltip>
            <!--删除 -->
            <el-tooltip effect="dark" content="删除用户" placement="top" :enterable="false">
            <el-button type="danger"  @click="deleteuser(scope.row.id)" icon="el-icon-delete" circle></el-button>
            </el-tooltip>
          <!-- 分配权限按钮 -->
          <el-tooltip effect="dark" content="设置用户权限" placement="top" :enterable="false">
            <el-button type="warning" icon="el-icon-setting" size="small"></el-button>
          </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

        <!--@size-change 每页显示记录条数变化触发事件
               @current-change 当前页变化触发事件
             :current-page 当前页 绑定请求参数
             :page-sizes 可选择的每页显示条数
                :page-size 当前显示条数 绑定请求参数
                layout分页布局显示 总条数、选择条数器等等…
                  : total 总条数 绑定data数据-->
      <!--分页区域-->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
    </el-row>
      </el-card>
  <!--对话框区域-->
  <div>
    <!--增加用户对话框 , :visible.sync设置显示或者隐藏对话框-->
    <el-dialog title="添加用户" :visible.sync="dialogTableVisible" @close="addclose" width="50%">
      <el-form :model="addform" :rules="addformrule"
               ref="addformref" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addform.username" ></el-input>
        </el-form-item>
        <el-form-item label=密码 prop="password">
          <el-input v-model="addform.password" >
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addform.email" >
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addform.mobile" >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduser">确 定</el-button>
      </div>
    </el-dialog >
    <!--修改用户区域对话框-->
    <el-dialog title="修改用户" :visible.sync="updatavisible" @close="updataclose" width="50%">
      <el-form :model="updataform" :rules="updataformrule"
               ref="updataformref" label-width="70px">
        <el-form-item label="用户名" >
          <el-input v-model="updataform.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updataform.email" >
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="updataform.mobile" >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updatavisible=false">取 消</el-button>
        <el-button type="primary" @click="updatauser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</div>

</template>

<script>
export default {
  name: "users",
  data() {
    const validatorPhone = (rule, value, callback) => {
      //手机号验证规则
      const reg = /^1[3|4|5|7|8][0-9]{9}$/;
      if (!reg.test(value)) {
        callback(new Error("手机号输入错误"));
      } else {
        callback();
      }
    };
    return {
      //获取用户列表参数对象
      queryInfo: {
        query: "",
        //当前的页数
        pagenum: 1,
        //当前每页显示多少条数据
        pagesize: 5
      },
      addform: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      addformrule: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 15, message: '长度在 6到 15个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10个字符', trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {validator: validatorPhone, trigger: "blur"},
          {min: 3, max: 12, message: '长度在 3 到 10个字符', trigger: 'blur'}
        ]
      },
      updataformrule: {
        email: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10个字符', trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {validator: validatorPhone, trigger: "blur"},
          {min: 3, max: 12, message: '长度在 3 到 10个字符', trigger: 'blur'}
        ]
      },
      updataform: {

      },
      userlist: [],
      total: 0,
      dialogTableVisible: false,
      updatavisible: false
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
//查询用户数据
    async getUserList() {
      const {data: res} = await this.$http.get('users', {params: this.queryInfo})
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户数据失败")
      }
      this.userlist = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    //表单预验证
    addclose() {
      this.$refs.addformref.resetFields()
    },
    updataclose() {
      this.$refs.addformref.resetFields()
    },

//增加用户
    adduser() {
      this.$refs.addformref.validate(async valid => {
        if (!valid) return
        const {data: res} = await this.$http.post('users', this.addform)
        if (res.meta.status !== 201) return this.$message.error('更新失败')
        this.$message.success('更新成功')
        //隐藏对话框
        this.dialogTableVisible = false
        //重新获取数据
        await this.getUserList()
      })
    },

    //修改用户
    async updatauser() {


      const {data: res} = await this.$http.put(`users/`+this.updataform.id,{
        email:this.updataform.email,
        mobile:this.updataform.mobile
      });
      if (res.meta.status !== 200)
        return this.$message.error("更新用户信息失败");

      this.updatavisible =false;
     await this.getUserList()

    },

    //删除用户
    // eslint-disable-next-line no-unused-vars
    async deleteuser(id) {
      const confirm = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      //如果返回confirm则表示用户确认删除
      //如果返回cancel则表示用户取消删除

      if (confirm !== 'confirm'){
        return this.$message.error("取消")
      }
       const {data:res}=await this.$http.delete('users/'+id)
      if(res.meta.status!==200){
        this.$message.error("删除失败")
      }
      await this.getUserList()
      return   this.$message.success("删除成功")

    },


    //监听pagesize改变事件
    handleSizeChange(newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },

    //监听页码值的改变
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
//用户状态
    async userStateChange(userinfo) {
      console.log(userinfo);
      const {data: res} = await this.$http.put(
          `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("更新用户列表失败");

      }
      this.$message.success("更新用户状态成功");
    },
    //清空搜索
    clearSearch() {
      this.queryInfo.query = ""
      this.getUserList()
    }
  }





}
</script>

<style scoped>

</style>
